/*
Copyright 2021 Alibaba Group Holding Limited.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package check

import (
	"sigs.k8s.io/controller-runtime/pkg/reconcile"

	polardbxv1polardbx "gitee.com/eezz10001/polardbx-operator/api/v1/polardbx"
	"gitee.com/eezz10001/polardbx-operator/pkg/k8s/control"
	polardbxv1reconcile "gitee.com/eezz10001/polardbx-operator/pkg/operator/v1/polardbx/reconcile"
)

func isStorageEngineConsistent(topology *polardbxv1polardbx.Topology) bool {
	if topology.Nodes.GMS.Template == nil {
		return true
	}

	dnEngine := topology.Nodes.DN.Template.Engine
	gmsEngine := topology.Nodes.GMS.Template.Engine

	// If any of the storages uses galaxy engine, then
	// they must be consistent.
	if gmsEngine == "galaxy" || dnEngine == "galaxy" {
		return gmsEngine == dnEngine
	}

	// Others should be fine.
	return true
}

var CheckStorageEngines = polardbxv1reconcile.NewStepBinder("CheckStorageEngines",
	func(rc *polardbxv1reconcile.Context, flow control.Flow) (reconcile.Result, error) {
		polardbx := rc.MustGetPolarDBX()

		if !isStorageEngineConsistent(&polardbx.Spec.Topology) {
			polardbx.Status.Phase = polardbxv1polardbx.PhaseFailed
			return flow.Break("Storage engines not consistent, transfer phase to failed.")
		}

		return flow.Pass()
	},
)
